#! /bin/sh
#
### BEGIN INIT INFO
# Provides:          supervisor
# Required-Start:    $remote_fs $network $named
# Required-Stop:     $remote_fs $network $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop supervisor
# Description:       Start/stop supervisor daemon and its configured
#                    subprocesses.
### END INIT INFO

. /lib/lsb/init-functions

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

PREFIX=/usr/local/bin
SUPERVISORD=$PREFIX/supervisord
SUPERVISORCTL=$PREFIX/supervisorctl
NAME=supervisord
PIDFILE=/var/run/supervisord.pid
OPTIONS="-c /etc/supervisor/supervisord.conf"
STOP_TIMEOUT=10
RETVAL=0

SCRIPT_OK=0
SCRIPT_ERROR=1

test -x $SUPERVISORD || exit 1

is_running() {
    # Check if the process is running looking at /proc
    # (works for all users)

    # No pidfile, probably no daemon present
    [ ! -f "$PIDFILE" ] && return 1
    # Obtain the pid and check it against the binary name
    pid=`cat $PIDFILE`
    (ps aux | grep -v grep | grep $SUPERVISORD | grep -q $pid) || return 1
    return 0
}

do_start() {
    log_daemon_msg "Starting $NAME: "

    if is_running; then
        log_end_msg $SCRIPT_ERROR
        echo "$NAME is already running."
        RETVAL=0
    else
        start-stop-daemon --start --quiet --pidfile $PIDFILE \
            --startas $SUPERVISORD -- $OPTIONS -j $PIDFILE
        [ -f $PIDFILE ] || sleep 1
        if is_running; then
            log_end_msg $SCRIPT_OK
            $SUPERVISORCTL $OPTIONS status
            RETVAL=0
        else
            log_end_msg $SCRIPT_ERROR
            RETVAL=1
        fi
    fi
}

do_stop() {
    log_daemon_msg "Stopping $NAME: "
    if is_running; then
        start-stop-daemon --stop --retry TERM/$STOP_TIMEOUT/KILL/5 --quiet --oknodo --pidfile $PIDFILE
        log_end_msg $SCRIPT_OK
        RETVAL=0
    else
        log_end_msg $SCRIPT_ERROR
        echo "$NAME is not running."
        RETVAL=0
    fi
}

chk_status() {
    echo -n "$NAME is "
    if is_running;  then
        echo "running."
        $SUPERVISORCTL $OPTIONS status
        RETVAL=0
    else
        echo "not running."
        RETVAL=0
    fi
}

case "$1" in
    start)
        do_start
        ;;
    stop)
        do_stop
        ;;
    restart)
        do_stop
        do_start
        ;;
    status)
        chk_status
        ;;
    *)
        echo "Usage: /etc/init.d/$NAME {start|stop|restart|status}"
        RETVAL=2
        ;;
esac

exit $RETVAL
